import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import type { RcFile } from 'antd/es/upload';
import React, { useState } from 'react';

import api from '@/apis/api';
import FileUploader from '@/components/FileUpload';
import { Logger } from '@/components/useLogger';
import localINFO from '@/utils/localInfo';

interface KeyImportModalProps {
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const KeyImportModal: React.FC<KeyImportModalProps> = ({ visible, setVisible }) => {
  const [form] = Form.useForm();
  const queryClient = useQueryClient();
  const [file, setFile] = useState<RcFile | null>(null);

  const ImportKey = useMutation({
    mutationFn: async (params: any) => {
      const formData = new FormData();
      if (file) {
        formData.append('file', file);
      }
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key]);
      });
      return api.ImportKey(formData);
    },
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('导入成功');
        form.resetFields();
        setVisible(false);
      } else {
        message.error(`导入失败, ${res?.message}`);
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('导入失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getKeyManageData'] }),
    mutationKey: ['getKeyManageData'],
  });

  const handleCreateOk = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    ImportKey.mutate(values);
  };

  const handleImportCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  return (
    <>
      <Modal
        title="密钥导入"
        open={visible}
        onOk={handleCreateOk}
        onCancel={handleImportCancel}
        cancelText="取消"
        okText="确定"
        destroyOnClose
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form form={form} preserve={false} autoComplete="off">
          <div style={{ marginBottom: '10px' }}>
            <span style={{ marginRight: '10px' }}>密钥访问控制码:</span>
            <div style={{ display: 'inline-block' }}>
              <Form.Item
                name="pinCode"
                style={{
                  marginBottom: 0,
                }}
                rules={[{ required: true, message: '请输入pinCode！' }]}
              >
                <Input.Password placeholder="请输入pinCode" />
              </Form.Item>
            </div>
          </div>
          <div style={{ marginBottom: '24px', marginTop: '24px' }}>
            <FileUploader setFile={setFile} />
          </div>
        </Form>
      </Modal>
    </>
  );
};

export default KeyImportModal;
